<template>
  <div class="draggable_content">
    <div class="header pl10 pr10">
      <el-input
        placeholder="请输入工程类型名称"
        :prefix-icon="Search"
        v-model="data.searchValue"
        @input="handelInputSerch"
      ></el-input>
    </div>
    <div class="content">
      <draggable
        v-if="data.myArray.length > 0"
        v-model="data.myArray"
        group="people"
        @start="drag = true"
        @end="onEnd"
        item-key="id"
      >
        <template #header></template>
        <template #item="{ element, index }">
          <div>
            <div class="file" @click="handelClickFirstFile(element, index)" :class="data.num == index ? 'active' : ''">
              <!-- <span v-if="element.list.length > 0">
                <el-icon size="20" color="#909399" v-if="element.isExpand"><CaretBottom /></el-icon>
                <el-icon size="20" color="#909399" v-else><CaretTop /></el-icon>
              </span> -->
              <!-- <img :src="fileImg" alt="" /> -->
              <div class="file_operate">
                <span>
                  <el-input
                    v-if="element.isEdit"
                    ref="autoFocus"
                    v-model="element.projectName"
                    :maxlength="15"
                    @blur="handelBlur(element)"
                    @focus="onFocus"
                    style="width: 115px"
                  ></el-input>
                  <!-- @focus="onFocus" -->
                  <span
                    v-else
                    style="white-space: nowrap; text-overflow: ellipsis; overflow: hidden; display: inline-block; width: 100px"
                    :title="element.projectName"
                    >{{ element.projectName }}</span
                  >
                </span>
                <div class="file_operate_right">
                  <!-- <img :src="move" alt="" /> -->
                  <div @click.stop>
                    <el-switch v-model="element.isStatus" @change="handelChnageStatus(element)" />
                    <el-popover placement="bottom" title="" :width="200" trigger="hover" :popper-class="'template-actionmore'">
                      <template #default>
                        <div class="action-wrap">
                          <p v-for="(item, i) in data.operateList" :key="i" @click="handelClickOperate(element, item)">
                            <el-button link :type="item.command === 'd' ? 'danger' : 'default'">{{ item.name }}</el-button>
                          </p>
                        </div>
                      </template>
                      <template #reference>
                        <span class="el-dropdown-link">
                          <el-icon><MoreFilled /></el-icon>
                        </span>
                      </template>
                    </el-popover>
                  </div>

                  <!-- <el-dropdown>
                    <span class="el-dropdown-link">
                      <img :src="more" alt="" />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          command="a"
                          v-for="(item, i) in data.operateList"
                          :key="i"
                          @click="handelClickOperate(element, item)"
                          >{{ item.name }}</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown> -->
                </div>
              </div>
            </div>
          </div>
        </template>
      </draggable>
      <div v-else style="display: flex; justify-content: center; width: 100%">
        <el-empty description="暂无数据" />
      </div>
    </div>
    <div class="add_file mt8">
      <el-button :icon="Plus" type="primary" @click="handelClickAddFile"> 新建工程类型 </el-button>
      <!-- <el-button :icon="Plus" type="primary" v-if="currNode.parentId !== 0" @click="handelClickAddFile"> 新建工程类型 </el-button> -->
    </div>
  </div>
</template>
<script setup>
// 资源导入
import { reactive, defineEmits, watch, defineProps, ref, nextTick } from "vue";
import draggable from "vuedraggable";
import { Search, Plus } from "@element-plus/icons-vue";
import more from "@/static/images/more.png";
import { ElMessage } from "element-plus";
// api
import { createProject, changeStatus, deleteProject, copyProject, projectUpdateSort } from "@/apis/createFile/index.js";
// 变量定义
const autoFocus = ref();
const emits = defineEmits(["addEngTypeList", "getTableList", "serch"]);
const props = defineProps({
  currNode: {
    type: Object,
    default: () => {}
  },
  list: {
    type: Array,
    required() {
      return [];
    }
  },
  item: {
    type: Object,
    required() {
      return {};
    }
  },
  saveLocalStore: {
    type: Function,
    default: null
  }
});
const data = reactive({
  searchValue: "",
  // 选中的数据
  selectedData: {},
  num: 0,
  // 拖动列表数据
  myArray: [
    // {
    //   id: 1,
    //   fileName: "文件夹2 1",
    //   isExpand: false,
    //   isEdit: false,
    //   list: [
    //     { id: 1, fileName: "文件夹2 16666", isExpand: true },
    //     { id: 2, fileName: "文件夹2 1666699999", isExpand: true }
    //   ]
    // }
  ],
  fileItem: [],
  operateList: [
    { id: 2, name: "编辑", command: "b" },
    { id: 3, name: "复制", command: "c" },
    { id: 4, name: "删除", command: "d" }
  ],
  operateListChildFile: [
    { id: 2, name: "编辑", command: "b" },
    { id: 3, name: "复制", command: "c" },
    { id: 4, name: "删除", command: "d" }
  ],
  engineeringTypeList: [],
  choseItem: {}
});
// 方法定义

const onFocus = event => {
  event.target.select();
  // console.log(909090, event);
};

const onEnd = prop => {
  console.log("拖拽结束", prop);
  data.num = prop.newIndex;
  const arr = JSON.parse(JSON.stringify(data.myArray));
  arr.map((item, index) => {
    item.showOrder = index + 1;
  });
  projectUpdateSort({ sortReqList: arr }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "拖拽排序修改成功",
        type: "success"
      });
    }
  });
};

const currObj = ref({});
const handelClickFirstFile = (item, index) => {
  currObj.value = item;
  props.saveLocalStore && props.saveLocalStore();
  // console.log(item, "工程文件点击.....");
  // 是否打开当前项
  // item.isExpand = !item.isExpand;
  // 赋值给选中的数据
  data.selectedData = item;
  data.num = index;
  emits("getTableList", item);
};
const handelInputSerch = v => {
  emits("serch", v);
};
// 新建工程文件
const handelClickAddFile = () => {
  if (Object.keys(props.item).length <= 0) {
    ElMessage({
      message: "请先选择定额模板",
      type: "warning"
    });
    return;
  }
  const parms = {
    ...data.fileItem,
    showOrder: data.myArray.length + 1
  };
  createProject(parms)
    .then(res => {
      if (res.code === 200) {
        console.log("成功");
        emits("addEngTypeList", data.fileItem, res.data);
      }
    })
    .catch(err => {
      console.log(err);
    });
};
// 更多操作
const handelClickOperate = (element, item) => {
  console.log(element, item);
  const command = item.command;
  if (command === "b") {
    element.isEdit = true;
    nextTick(() => {
      // autoFocus.value.select();
      // autoFocus.value.focus();
    });
  } else if (command === "a") {
    // element.list.push(childrenItem);
  } else if (command === "d") {
    // element.list.push(childrenItem);
    deleteProject(element.projectId).then(() => {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      emits("addEngTypeList", data.engineeringTypeList);
    });
  } else if (command === "c") {
    copyProject(element.projectId).then(() => {
      ElMessage({
        message: "复制成功",
        type: "success"
      });
      emits("addEngTypeList", data.engineeringTypeList);
    });
  }
};
// 失去焦点时保存当前文件的名称并不让在编辑
const handelBlur = element => {
  element.isEdit = false;
  createProject(element)
    .then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "名称修改成功",
          type: "success"
        });
        emits("addEngTypeList");
      }
    })
    .catch(err => {
      console.log(err);
    });
};
const handelChnageStatus = item => {
  console.log(item.status);
  changeStatus({
    projectId: item.projectId,
    status: item.isStatus == true ? 1 : 0
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: item.isStatus == true ? "工程启用成功" : "工程禁用成功",
        type: "success"
      });
      emits("addEngTypeList", data.engineeringTypeList);
    }
  });
};
// 生命周期
// 监听
watch(
  () => props.list,
  list => {
    // 赋值给渲染列表
    data.myArray = JSON.parse(JSON.stringify(list));

    const quotaAtore = JSON.parse(localStorage.getItem("quota"));
    const folderId2 = quotaAtore?.folderId2;
    if (folderId2) {
      //有缓存，设置默认值
      const quotaAtore = JSON.parse(localStorage.getItem("quota"));
      const index = data.myArray.findIndex(item => item.projectId === quotaAtore.folderId2);
      const obj = data.myArray.find(item => item.projectId === quotaAtore.folderId2);
      data.num = index;
      currObj.value = obj;
      props.saveLocalStore && props.saveLocalStore();

      const ids = list.map(item => item.projectId) || [];
      if (!ids.includes(folderId2)) {
        data.num = 0; //默认选中第一个
        currObj.value = data.myArray[0];
        props.saveLocalStore && props.saveLocalStore();
      }
      emits("getTableList", currObj.value); //查询数据
    } else {
      // 没有缓存
      data.num = 0; //默认选中第一个
      currObj.value = data.myArray[0];
      props.saveLocalStore && props.saveLocalStore();
      emits("getTableList", currObj.value); //查询数据
    }
  },
  { deep: true }
);
watch(
  () => props.item,
  list => {
    data.fileItem = list;
  },
  { deep: true, immediate: true }
);

defineExpose({ currObj, handelClickFirstFile });
</script>

<style lang="scss">
.template-actionmore {
  min-width: auto !important;
  width: 120px !important;
  border-radius: 6px !important;
  box-sizing: border-box !important;
  .el-button {
    width: 100%;
    justify-content: flex-start !important;
    line-height: 26px !important;
    font-size: 12px !important;
  }

  .action-wrap {
    .el-button.el-button--default.is-link {
      &:hover {
        color: #007dff;
      }
    }
    .el-button.el-button--danger.is-link {
      &:hover {
        color: red;
      }
    }
  }
}
</style>
<style scoped lang="scss">
.active {
  background-color: #d9e8ff !important;
}
.file_operate {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;
  &_right {
    display: flex;
    align-items: center;
    padding-right: 5px;
  }
}
.draggable_content {
  padding: 20px 0;
  width: 201px;
  height: calc(100% - 40px);
  background-color: #fff;
  overflow: hidden;
  border-right: 1px solid #c2d4e8;
  .header {
    font-size: 18px;
    color: #131414;
    // padding: 20px;
    overflow: hidden;
    :deep(.el-input__wrapper) {
      background-color: #fff !important;
    }
  }
}
// 拖拽外层内容css
.content {
  margin-top: 10px;
  height: calc(100% - 90px);
  overflow: auto;
}
.file {
  width: 100%;
  height: 44px;
  display: flex;
  align-items: center;
  cursor: pointer;
  box-sizing: border-box;
  img {
    width: 16px;
  }
  span {
    margin-left: 10px;
    i {
      transform: rotate(90deg);
    }
  }

  &.active {
    .file_operate_right {
      .el-dropdown-link {
        color: #007dff;
      }
    }
  }
}
.child_file {
  padding-left: 20px;
  width: 100%;
  height: 44px;
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #000;
  box-sizing: border-box;
  span {
    margin-left: 10px;
  }
  img {
    width: 16px;
  }
}
.add_file {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
